package com.ttpai.boot.lbs.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ttpai.boot.lbs.dao.MetroPointRawDAO;
import com.ttpai.boot.lbs.model.MetroPointRawVO;
import com.ttpai.boot.lbs.util.JsoupUtil;
import com.ttpai.boot.lbs.util.StringUtil;
import com.ttpai.boot.lbs.util.UrlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by Kail on 2017/3/2.
 * Copyright(c) ttpai All Rights Reserved.
 */
@Service
public strictfp class MetroPointRawService {

    @Autowired
    private BaiduLbsService lbsService;
    @Autowired
    private MetroPointRawDAO metroPointRawDAO;

    private static final Logger logger = LoggerFactory.getLogger(MetroPointRawService.class);

    private Map<String, Integer> CACHE_ALL_BAIDU_CITY = null;


    public List<MetroPointRawVO> selectMetroPoint(String city, String lineName) {
        MetroPointRawVO select = new MetroPointRawVO();
        select.setCityName(city);
        select.setLineName(lineName);
        return metroPointRawDAO.selectAllMetroPoint(select);
    }



    /* =========================================================================================================================================================== */
    /* =========================================================================================================================================================== */
    /* =========================================================================================================================================================== */


    /**
     * 获取所有[城市-ID]
     */
    public Map<String, Integer> selectBaiduMetorCity() {
        String allCityUrl = "http://ditu.baidu.com/?qt=subwayscity";
        String allCityJson = JsoupUtil.getBodyText(allCityUrl);
        JSONObject jsonObject = JSON.parseObject(allCityJson);
        JSONObject subwaysCity = jsonObject.getJSONObject("subways_city");
        JSONArray cities = subwaysCity.getJSONArray("cities");

        if (null == CACHE_ALL_BAIDU_CITY || CACHE_ALL_BAIDU_CITY.isEmpty()) {
            CACHE_ALL_BAIDU_CITY = new HashMap<>();
            Iterator<Object> iterator = cities.iterator();
            for (; iterator.hasNext(); ) {
                JSONObject cityJson = (JSONObject) iterator.next();
                CACHE_ALL_BAIDU_CITY.put(cityJson.getString("cn_name"), cityJson.getInteger("code"));
            }
        }
        return CACHE_ALL_BAIDU_CITY;
    }

    /**
     * 获取城市[地铁名称信息]
     */
    public void insertBaiduMetroCity(Integer code, String cityName) {
        List<MetroPointRawVO> metroPointRawVOS = fetchBaiduMetorCity(code, cityName);

        for (MetroPointRawVO metroPointVO : metroPointRawVOS) {
            metroPointRawDAO.insertMetroPoint(metroPointVO);
        }
    }

    public List<MetroPointRawVO> fetchBaiduMetorCity(Integer code, String cityName) {
        String text = JsoupUtil.getBodyText("http://ditu.baidu.com/?qt=bsi&c=" + code);

        List<MetroPointRawVO> allPoint = new ArrayList<>();

        JSONObject jsonObject = JSON.parseObject(text);
        JSONArray content = jsonObject.getJSONArray("content");
        Iterator<Object> iterator = content.iterator();
        for (; iterator.hasNext(); ) {
            JSONObject line = (JSONObject) iterator.next();

            String metroLineName = line.getString("line_name");
            JSONArray stops = line.getJSONArray("stops");
            Iterator<Object> stopsIt = stops.iterator();
            for (; stopsIt.hasNext(); ) {
                JSONObject stopInfo = (JSONObject) stopsIt.next();

                String name = stopInfo.getString("name");
                if (org.apache.commons.lang.StringUtils.isNotBlank(name)) {
                    MetroPointRawVO metroPointVO = new MetroPointRawVO();
                    metroPointVO.setMetroLineName(metroLineName);
                    metroPointVO.setCityName(cityName);

                    metroPointVO.setIsPractical(stopInfo.getInteger("is_practical"));
                    metroPointVO.setName(name);
                    metroPointVO.setLineName(StringUtil.findStrByRegex(metroLineName, "(.*?)\\(", 1));
                    metroPointVO.setUid(stopInfo.getString("uid"));
                    metroPointVO.setX(stopInfo.getDouble("x"));
                    metroPointVO.setY(stopInfo.getDouble("y"));

                    allPoint.add(metroPointVO);
                }
            }
        }

        return allPoint;
    }


    DecimalFormat decimalFormat = new DecimalFormat("###0.##");//格式化设置

    public Integer fetchMetroPointTime(String suid, Double sx, Double sy, String sname, String euid, Double ex, Double ey, String ename, Integer ccode) {
//        String url = "http://ditu.baidu.com/?qt=bt&sn=0$$cedb33067cf66173911fc9de$$13509440.57000,3631413.78000$$%E4%B8%83%E5%AE%9D$$&en=0$$0492d312a0a8ae1d8bfc061a$$13518415.95,3641631.11$$%E6%AD%A6%E5%AE%81%E8%B7%AF$$&m=sbw";
        String url = String.format("http://ditu.baidu.com/?qt=bt&sn=0$$%s$$%s,%s$$%s$$&en=0$$%s$$%s,%s$$%s$$&m=sbw&from=dtzt&c=%s",
                suid, decimalFormat.format(sx), decimalFormat.format(sy), UrlUtil.encode(sname),
                euid, decimalFormat.format(ex), decimalFormat.format(ey), UrlUtil.encode(ename),
                ccode
        );

        String bodyText = JsoupUtil.getBodyText(url);

        try {
            JSONObject jsonObject = JSON.parseObject(bodyText);
            JSONObject content = jsonObject.getJSONArray("content").getJSONObject(0);
            JSONObject exts = content.getJSONArray("exts").getJSONObject(0);
            return exts.getInteger("time");
        } catch (Exception e) {
            System.out.println(url);
            System.out.println(bodyText);
            throw e;
        }
    }


    /**
     * 抓取地铁站的经纬度
     */
    public void updateMetroLngLat(String city) {
        List<MetroPointRawVO> metroPointVOS = this.selectMetroPoint(city, null);
        for (MetroPointRawVO metroPoint : metroPointVOS) {
            if (null == metroPoint.getLng() || metroPoint.getLng().equals(0D)) {
                String[] lnglat = lbsService.fetchLngLat(metroPoint.getCityName(),
                        StringUtil.findStrByRegex(metroPoint.getMetroLineName(), "(地铁[0-9]{1,2}号线)") + metroPoint.getName()).split(",");
                metroPoint.setLng(Double.valueOf(lnglat[0]));
                metroPoint.setLat(Double.valueOf(lnglat[1]));
                metroPointRawDAO.updateMetroPoint(metroPoint);
            }
        }
    }


    public static void main(String[] args) throws IOException {
//        System.out.println("asdf()（）sad-asd".replaceAll("[\\(\\)（）\\-]", ""));
//        System.out.println(new BaiduLbsExtService().selectBaiduMetorCity());


        // 2c7a5907ba85655ecbe33cde	七宝	13509440.57000	3631413.78000
        // af89910ff0217e2e343a710f	武宁路	13518415.95000	3641631.11000
        // f91f4d2c6c3b0e5e09ccddcd	丰庄	13510123.41000	3642677.36000
        // f20e942b7f7aa865f6c59ce2	顾村公园	13512030.32000	3655927.45000
        // 8faf6d7286a7191938221c97	沙园	12608944.30000	2626545.19000
        // a3cca5e2f91d160e6dc02ccd	礌岗	12597253.25000	2621104.22000

//        DecimalFormat decimalFormat = new DecimalFormat("###0.##");//格式化设置
//        System.out.println(decimalFormat.format(2626545.19));
//        System.exit(1);

        MetroPointRawService metroPointRawService = new MetroPointRawService(); // http://ditu.baidu.com/?qt=subwayscity

        Integer code = 138;
        String cityName = "佛山市";
//        List<MetroPointRawVO> metroPointRawVOS = metroPointRawService.fetchBaiduMetorCity(289, "上海市");
        List<MetroPointRawVO> metroPointRawVOS = metroPointRawService.fetchBaiduMetorCity(code, "佛山市");

        Map<String, MetroPointRawVO> map = new HashMap<>();
        for (MetroPointRawVO metroPointRawVO : metroPointRawVOS) {
            map.put(metroPointRawVO.getName(), metroPointRawVO);
        }
        MetroPointRawVO start = map.get("燕岗");
        MetroPointRawVO end = map.get("礌岗");


        System.out.println(new MetroPointRawService().fetchMetroPointTime(
                start.getUid(), start.getX(), start.getY(), start.getName(),
                end.getUid(), end.getX(), end.getY(), end.getName(),
//                "f20e942b7f7aa865f6c59ce2", 13512030.32000, 3655927.45000, "顾村公园",
//                "dea58ffbb52a4b9a9ff779ca", 12608944.30000, 2626545.19000, "沙园",
//                "20d705b091be753e06026fff", 12597253.25, 2621104.22, "礌岗",
                code
        ));

        // http://ditu.baidu.com/?qt=bt&sn=0$$dea58ffbb52a4b9a9ff779ca$$12608944.3,2626545.19$$%E6%B2%99%E5%9B%AD$$&en=0$$20d705b091be753e06026fff$$12597253.25,2621104.22$$%E7%A4%8C%E5%B2%97$$&m=sbw&from=dtzt&c=257
        // http://ditu.baidu.com/?qt=bt&sn=0$$8faf6d7286a7191938221c97$$12608944.3,2626545.19$$%E6%B2%99%E5%9B%AD$$&en=0$$a3cca5e2f91d160e6dc02ccd$$12597253.25,2621104.22$$%E7%A4%8C%E5%B2%97$$&m=sbw&from=dtzt&c=257


    }

}
